package com.wohuijituan.whcsmerchant.fragment;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.activity.GoodsCompileActivity;
import com.wohuijituan.whcsmerchant.activity.GoodsManageActivity;
import com.wohuijituan.whcsmerchant.adapter.GoodsListAdapter;
import com.wohuijituan.whcsmerchant.bean.CommonBean;
import com.wohuijituan.whcsmerchant.bean.ShopGoodsListBean;
import com.wohuijituan.whcsmerchant.bean.ShopGoodsListBean.DataEntity.GoodsEntity;
import com.wohuijituan.whcsmerchant.callback.CommonCallBack;
import com.wohuijituan.whcsmerchant.callback.ShopGoodsListCallBack;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.ExtraName;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyOkHttpUtils;
import com.wohuijituan.whcsmerchant.utils.MyRequestParams;
import com.wohuijituan.whcsmerchant.utils.MyUtile;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 */
public class GoodsSellFragment extends MyBaseFragment implements View.OnClickListener{
    public static final String TAG = "GoodsSellFragment";
    public static final int STYLE_ONSELL = 10;//上架的
    public static final int STYLE_UNSELL = 20;//下架的
    public static final int STYLE_SEARCH = 30;//搜索的
    public static final int GoodsStateSet_OK = 1215;
    public static final int GoodsStoreSet_OK = 1225;
    public static final int ShopGoodsList_OK = 4547;
    private int style;//当前展示商品的类型,上架的或者下架的
    private LinearLayout popLayout;
    private LinearLayout llGoodsCompile;
    private LinearLayout llGoodsUnShelve;
    private LinearLayout llGoodsRemainCompile;
    private TextView tvSell;
    private MyOkHttpUtils myOkHttpUtils;
    private ImageView ivSell;
    private MyRequestParams params;
    private int nowPage = 1;//当前显示页数
    private int totalPage;//订单总页数
    private int pageNumber = 10;//每页显示个数
    private List<GoodsEntity> goodsList;
    private GoodsManageActivity activity;
    private String categoryName;//传入参数,商品分类名称
    private String categoryNumber;//传入数据,商品分类GUID
    private int position;//当前弹窗代表的商品条目位置
    private String keyWord = "";//搜索的关键字
    private void assignViews(View v) {
        llGoodsCompile = (LinearLayout) v.findViewById(R.id.ll_goods_compile);
        llGoodsUnShelve = (LinearLayout) v.findViewById(R.id.ll_goods_un_shelve);
        llGoodsRemainCompile = (LinearLayout) v.findViewById(R.id.ll_goods_remain_compile);
        ivSell = (ImageView) v.findViewById(R.id.iv_sell);
        tvSell = (TextView) v.findViewById(R.id.tv_sell);
    }
    public static GoodsSellFragment newInstance(int style){
        GoodsSellFragment fragment = new GoodsSellFragment();
        Bundle data = new Bundle();
        data.putInt("style",style);
        fragment.setArguments(data);
        return fragment;
    }
    private GoodsListAdapter myAdapter;
    private PullToRefreshListView pullGoodsList;
    @Override
    public View createMyView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_goods_list, container, false);
        initData();
        initView(v);
        initListener();
        if (style!=STYLE_SEARCH){
            goodsListRequest(categoryNumber, 1, pageNumber, style);
        }
        return v;
    }

    private void initData() {
        style = getArguments().getInt("style",STYLE_ONSELL);
        myOkHttpUtils = new MyOkHttpUtils();
        params = new MyRequestParams();
        if (style!=STYLE_SEARCH){
            activity  = (GoodsManageActivity) getActivity();
            categoryName = activity.getCategoryName();
            categoryNumber = activity.getCategoryNumber();
        }
        goodsList = new ArrayList<>();
        myAdapter = new GoodsListAdapter(ctx,goodsList);

    }

    private void initView(View v) {
        //初始化界面
        pullGoodsList = (PullToRefreshListView) v.findViewById(R.id.pull_goods_list);
        pullGoodsList.setMode(PullToRefreshBase.Mode.BOTH);
        //得到弹窗控件,并得到其内部控件
        popLayout = (LinearLayout) LayoutInflater.from(ctx).inflate(R.layout.pop_compile_goods,pullGoodsList,false);
        assignViews(popLayout);
        pullGoodsList.setAdapter(myAdapter);
    }

    private void initListener() {
        llGoodsCompile.setOnClickListener(this);
        llGoodsRemainCompile.setOnClickListener(this);
        llGoodsUnShelve.setOnClickListener(this);
        myAdapter.setMyOnItemBtnClickListener(new GoodsListAdapter.MyOnItemBtnClickListener() {
            @Override
            public void onClick(int position, View view) {
                LogUtils.e(TAG, view.getLeft() + "***" + view.getRight());
                GoodsSellFragment.this.position = position;
                showPopupWindow(view);
            }
        });
        pullGoodsList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (style!=STYLE_SEARCH){
                    goodsListRequest(categoryNumber, 1, pageNumber, style);
                }else {
                    searchGoodsRequest(keyWord,1,pageNumber);
                }
            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (nowPage < totalPage) {
                    if (style!=STYLE_SEARCH){
                        //得到下一页数据
                        goodsListRequest(categoryNumber, nowPage + 1, pageNumber, style);
                    }else {
                        searchGoodsRequest(keyWord,nowPage+1,pageNumber);
                    }
                    //得到下一页数据
                    goodsListRequest(categoryNumber, nowPage + 1, pageNumber, style);
                } else {
                    showToast(ctx, "已经是最后一页");
                    pullGoodsList.onRefreshComplete();
                }

            }
        });
    }
    /**
     * 进行搜索,public方法,外部调用
     * @param keyWord
     */
    public void doSearchGoods(String keyWord){
            this.keyWord = keyWord;
            searchGoodsRequest(keyWord,1,pageNumber);
    }
    /**
     * 搜索商品的网络请求
     * @param keyWord
     */
    private void searchGoodsRequest(String keyWord,int pageIndex,int rows){
        showDialog(ctx);
        params.clear();
        String strUrl = Urls.ShopGoodsSearch;
        params.addStringRequest(ParamsKey.UserKey,myApplication.getUserKey());
        params.addStringRequest(ParamsKey.ShopGoodsSearch_KeyWord,keyWord);
        params.addStringRequest(ParamsKey.ShopGoodsList_PageIndex,pageIndex+"");
        params.addStringRequest(ParamsKey.ShopGoodsSearch_Rows,rows+"");
        myOkHttpUtils.postRequest(strUrl,params,shopGoodsListCallBack );
    }
    /**
     * 网络请求获得商家的商品列表
     * @param categoryNumber 第三级类别的guid
     * @param pageIndex 当前页数
     * @param rows 每页数量
     * @param mode 上架:10,下架20
     */
    private void goodsListRequest(String categoryNumber, int pageIndex, int rows, int mode){
        showDialog(ctx);
        String strUrl = Urls.ShopGoodsList;
        params.clear();
        params.addStringRequest(ParamsKey.ShopGoodsList_ShopNumber, myApplication.getUserKey());
        params.addStringRequest(ParamsKey.ShopGoodsList_Category, categoryNumber);
        params.addStringRequest(ParamsKey.ShopGoodsList_Mode, mode + "");
        params.addStringRequest(ParamsKey.ShopGoodsList_PageIndex, pageIndex + "");
        params.addStringRequest(ParamsKey.ShopGoodsList_Rows, rows + "");
        myOkHttpUtils.postRequest(strUrl, params,shopGoodsListCallBack);
    }

    /**
     * 上架下架商品
     * @param shopGoodsSN 当前商家的商品列表中的商品唯一标示
     * @param state 给商品设置的状态,上架:10,下架:20
     */
    private void goodsStateSetRequest(String shopGoodsSN,int state){
        showDialog(ctx);
        String strUrl = Urls.ShopGoodsSateSet;
        params.clear();
        params.addStringRequest(ParamsKey.SetSate_ShopGoodsNumber, shopGoodsSN);
        params.addStringRequest(ParamsKey.SetSate_State, state + "");
        myOkHttpUtils.postRequest(strUrl, params, new CommonCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
                dismissDialog();
            }

            @Override
            public void onResponse(CommonBean response, int id) {
                dismissDialog();
                if (response.getState() == 1) {

                    handler.sendEmptyMessage(GoodsStateSet_OK);
                    showToast(ctx, "操作成功:" + response.getMsg());
                } else {
                    showToast(ctx, "操作失败:" + response.getMsg());
                }
            }
        });
    }

    /**
     * 商品余量编辑请求方法
     * @param shopGoodsSN
     * @param store
     */
    private void goodsStoreEditRequest(String shopGoodsSN, final int store){
        showDialog(ctx);
        String strUrl = Urls.GoodsStoreEdit;
        params.clear();
        params.addStringRequest(ParamsKey.GoodsStoreEdit_GoodsGUID, shopGoodsSN);
        params.addStringRequest(ParamsKey.GoodsEdit_Store,store+"");
        myOkHttpUtils.postRequest(strUrl, params, new CommonCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
                dismissDialog();
            }

            @Override
            public void onResponse(CommonBean response, int id) {
                dismissDialog();
                if (response.getState() == 1) {
                    Message msg = new Message();
                    msg.what = GoodsStoreSet_OK;
                    msg.obj = store;
                    handler.sendMessage(msg);
                    showToast(ctx, "操作成功:" + response.getMsg());
                } else {
                    showToast(ctx, "操作失败:" + response.getMsg());
                }
            }
        });
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case ShopGoodsList_OK:
                    // 商品列表请求成功
                    ShopGoodsListBean bean = (ShopGoodsListBean) msg.obj;
                    nowPage = bean.getData().getPageIndex();
                    totalPage = bean.getData().getPageCount();
                    if (nowPage ==1){
                        myAdapter.replace(bean.getData().getData());
                        LogUtils.e(TAG, nowPage + "数据个数:" + bean.getData().getData().size());
                    }else if (nowPage>1){
                        myAdapter.addAll(bean.getData().getData());
//                        goodsList.addAll(bean.getData().getData());
//                        myAdapter.notifyDataSetChanged();
                    }
                    dismissDialog();
                    break;
                case GoodsStateSet_OK:
                    //商品上架、下架成功
                    myAdapter.sub(position);
                    break;
                case GoodsStoreSet_OK:
                    //商品库存修改成功
                    int store = (int) msg.obj;
                    goodsList.get(position).setSMC_StockNum(store);
                    myAdapter.notifyDataSetChanged();

            }
        }
    };
    PopupWindow popWindow;
    /**
     * 弹窗编辑商品
     * @param v
     */
    private void showPopupWindow(View v) {
        popWindow = new PopupWindow(
                popLayout,
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT
                ,true);
        if (goodsList.get(position).getSMC_Status()==STYLE_ONSELL){
            ivSell.setImageDrawable(ctx.getResources().getDrawable(R.drawable.tab_unsale));
            tvSell.setText(R.string.goods_un_shelve);
        }else {
            ivSell.setImageDrawable(ctx.getResources().getDrawable(R.drawable.tab_sale));
            tvSell.setText(R.string.goods_shelve);
        }
        popWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_pop ));
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        LogUtils.e(TAG,"location[0]"+location[0]+"v.getWidth()"+v.getWidth()+"popLayout.getWidth()"+popLayout.getWidth());
        int x = -v.getWidth()- MyUtile.getViewHeight(popLayout,false);
        int y = -v.getMeasuredHeight()/2-MyUtile.getViewHeight(popLayout,true)/2;
//        popWindow.showAtLocation(v, (location[0]-v.getWidth()-popLayout.getWidth()), location[1]-v.getHeight()/2);
        popWindow.showAsDropDown(v, x, y);
    }
    public static final int EditRequestCode = 10;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_goods_compile://TODO 编辑商品
                GoodsEntity data = goodsList.get(position);
                Intent intent = new Intent(ctx, GoodsCompileActivity.class);
                intent.putExtra(ExtraName.SHOPGOODS_BEAN,data);
                intent.putExtra(ExtraName.TAG,TAG);
                startActivityForResult(intent, EditRequestCode);
                popWindow.dismiss();
                break;
            case R.id.ll_goods_un_shelve://TODO 下架商品
                data = goodsList.get(position);
                if (data.getSMC_Status()==STYLE_ONSELL){
                    goodsStateSetRequest(data.getSMC_GUID(),STYLE_UNSELL);
                }else if (data.getSMC_Status()==STYLE_UNSELL){
                    goodsStateSetRequest(data.getSMC_GUID(),STYLE_ONSELL);
                }
                popWindow.dismiss();
                break;
            case R.id.ll_goods_remain_compile://TODO 余量编辑机
                data = goodsList.get(position);
                showCompileDialog(data.getSMC_GUID());
                popWindow.dismiss();
                break;
            case 1:
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.e(TAG,requestCode+"resultCode"+resultCode);
        if (requestCode==EditRequestCode){
            if (resultCode== Activity.RESULT_FIRST_USER){
                LogUtils.e(TAG,"resultCode:"+resultCode);
                if (style!=STYLE_SEARCH){
                    //得到下一页数据
                    goodsListRequest(categoryNumber, nowPage + 1, pageNumber, style);
                }else {
                    searchGoodsRequest(keyWord,nowPage+1,pageNumber);
                }
                myAdapter.notifyDataSetChanged();
            }
        }
    }
    /**
     * 弹出一个dialog让用户修改信息
     * @param shopGoodsSN 当前商家的商品列表中商品的唯一标示
     */
    private void showCompileDialog(final String shopGoodsSN){
        final EditText et = new EditText(ctx);
        et.setSingleLine(true);
        //直接调出输入数字软键盘
        et.setInputType(InputType.TYPE_CLASS_NUMBER );
        new AlertDialog.Builder(ctx).setTitle("库存")
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();

                        if (input.equals("")) {
                            showToast(ctx,"输入不能为空");
                        } else {
                            int store = Integer.parseInt(input);
                            goodsStoreEditRequest(shopGoodsSN,store);
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
    /**
     * 商品列表请求回调,搜索和列表
     */
    ShopGoodsListCallBack shopGoodsListCallBack = new ShopGoodsListCallBack() {
        @Override
        public void onError(Call call, Exception e, int id) {
            dismissDialog();
            showToast(ctx, "网络出错,请检查网络是否连接!");
            LogUtils.e(TAG, e.getMessage());
            pullGoodsList.onRefreshComplete();
        }

        @Override
        public void onResponse(ShopGoodsListBean response, int id) {
            if (response.getState() == 1) {
                Message msg = new Message();
                msg.what = ShopGoodsList_OK;
                msg.obj = response;
                handler.sendMessage(msg);
            } else if (response.getState() == 0) {
                showToast(ctx, "服务器数据为空");
            } else {
                showToast(ctx, response.getMsg());
                dismissDialog();
            }
            pullGoodsList.onRefreshComplete();
        }
    };
}
